//
//  QXOAuthVC.m
//  QXWeibo2
//
//  Created by QinXin on 15/7/4.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

#import "QXOAuthVC.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <AFNetworking/AFNetworking.h>
#import "QXNetworking.h"
#import "QXAccount.h"
#import "QXUser.h"
#import "QXMainVC.h"

/// 申请应用时分配的AppKey
#define k_client_id @"2333485825"
/// 授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址
#define k_redirect_uri @"http://www.baidu.com"
/// 申请应用时分配的AppSecret
#define k_app_secret @"a48c3dbe00b3bf1a3c998b79d6eb72ea"

@interface QXOAuthVC () <UIWebViewDelegate>

@end

@implementation QXOAuthVC

/// 加载视图
- (void)loadView {
    UIWebView *webView = [[UIWebView alloc] init];
    webView.delegate = self;
    self.view = webView;
}

/// 加载完成
- (void)viewDidLoad {
    [self startOAuth];
}

/// 开始授权
- (void)startOAuth {
    NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", k_client_id, k_redirect_uri];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [(UIWebView *)self.view loadRequest:request];
}

/// 根据请求码，取得授权数据
- (void)getAcountDicWithCode:(NSString *)code {
    NSDictionary *params = @{
                             @"client_id": k_client_id,
                             @"client_secret": k_app_secret,
                             @"grant_type": @"authorization_code",
                             @"code": code,
                             @"redirect_uri": k_redirect_uri,
                             };
    
    // 从网络获取用户的授权信息（dic）
    [[QXNetworking sharedNetworking] POST:@"oauth2/access_token" parameters:params success:^(NSURLSessionDataTask *task, id dic) {
        
        QXAccount *account = [QXAccount accountWithDic:dic];
        [account achiveToSharedPath];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"QXAppDelegateNeedsChangeViewController" object:self userInfo:@{@"class": [QXMainVC class]}];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
    }];
    
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidStartLoad:(nonnull UIWebView *)webView {
    [SVProgressHUD show];
}

- (void)webViewDidFinishLoad:(nonnull UIWebView *)webView {
    [SVProgressHUD dismiss];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    if (![request.URL.absoluteString hasPrefix:k_redirect_uri]) {
        return YES;
    }
    
    NSString *query = request.URL.query;
    
    if ([query hasPrefix:@"code="]) {
        NSRange range =[query rangeOfString:@"code="];
        NSString *code = [query substringFromIndex:range.length];
        [self getAcountDicWithCode:code];
    }
    
    return NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [SVProgressHUD dismiss];
}

@end
